package org.madrox.core.controllers;

import java.io.IOException;
import java.util.Arrays;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("/oauth2callback")
public class OAuth2CallbackController {

	@RequestMapping(method=RequestMethod.GET)
	public void doCallback(@RequestParam(value="code", required=false) String[] code,
			@RequestParam(value="error", required=false) String[] error,
			HttpServletResponse resp) {
		
		// Checking if there was an error such as the user denied access
	    if (error != null && error.length > 0) {
	      try {
			resp.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "There was an error: \""+error[0]+"\".");
		} catch (IOException e) {
			// TODO log exception
			e.printStackTrace();
		}
	      return;
	    }

	    // Checking conditions on the "code" URL parameter
	    if (code == null || code.length == 0) {
	      try {
			resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "The \"code\" URL parameter is missing");
		} catch (IOException e) {
			// TODO log exception
			e.printStackTrace();
		}
	      return;
	    }
	    
	    System.out.println(Arrays.toString(code));	    
		
	}
}